package job

import (
	"context"
	"time"
)

type Handler func(ctx context.Context) bool

type OptionFunc func(opts *Options)

var WithContext = func(ctx context.Context) OptionFunc {
	return func(opts *Options) {
		opts.ctx = ctx
	}
}

var WithHandler = func(handler Handler) OptionFunc {
	return func(opts *Options) {
		opts.handler = handler
	}
}

type Options struct {
	ctx     context.Context
	handler Handler
}

func Run(opt ...OptionFunc) {

	var opts Options
	for _, o := range opt {
		o(&opts)
	}
	if opts.ctx == nil {
		opts.ctx = context.Background()
	}
	forever(opts.ctx, opts.handler)
}

func forever(ctx context.Context, handler Handler) {
	if handler == nil {
		return
	}
	for {
		select {
		case <-ctx.Done():
			return
		default:
			hasNext := handler(ctx)
			if !hasNext {
				return
			}
			time.Sleep(time.Second * 5)
		}
	}
}
